// 测试UTF-8编码修复
// 文件：test-utf8-fix.js

/**
 * 模拟后端接收到的乱码文件名
 */
function testUtf8Decoding() {
  console.log('🚀 开始测试UTF-8编码修复\n');
  
  // 模拟从Multer接收到的乱码文件名
  const testCases = [
    {
      input: 'ä¸è½½.png',
      expected: '下载.png',
      description: 'UTF-8乱码文件名'
    },
    {
      input: 'æµè½½.pdf',
      expected: '下载.pdf', 
      description: '另一个UTF-8乱码文件名'
    },
    {
      input: 'test-document.docx',
      expected: 'test-document.docx',
      description: '英文文件名（无需处理）'
    },
    {
      input: '微信图片.png',
      expected: '微信图片.png',
      description: '正常中文文件名'
    }
  ];
  
  console.log('=== 测试UTF-8解码 ===');
  
  testCases.forEach((testCase, index) => {
    console.log(`\n${index + 1}. ${testCase.description}`);
    console.log(`   输入: ${testCase.input}`);
    console.log(`   期望: ${testCase.expected}`);
    
    // 检查是否是URL编码
    if (testCase.input.includes('%')) {
      try {
        const decoded = decodeURIComponent(testCase.input);
        console.log(`   URL解码: ${decoded} ${decoded === testCase.expected ? '✅' : '❌'}`);
      } catch (error) {
        console.log(`   URL解码失败: ${error.message}`);
      }
    }
    
    // 检查是否是UTF-8乱码
    const hasUtf8Garbled = /[äåçèéêëìíîïðñòóôõöøùúûüýþÿ]/.test(testCase.input);
    if (hasUtf8Garbled) {
      try {
        const buffer = Buffer.from(testCase.input, 'latin1');
        const decoded = buffer.toString('utf8');
        console.log(`   UTF-8解码: ${decoded} ${decoded === testCase.expected ? '✅' : '❌'}`);
      } catch (error) {
        console.log(`   UTF-8解码失败: ${error.message}`);
      }
    }
    
    // 检查是否包含中文字符
    const hasChinese = /[\u4e00-\u9fa5]/.test(testCase.input);
    if (hasChinese) {
      console.log(`   中文检测: 包含中文字符 ✅`);
    } else {
      console.log(`   中文检测: 不包含中文字符`);
    }
  });
}

/**
 * 测试Buffer编码转换
 */
function testBufferConversion() {
  console.log('\n=== Buffer编码转换测试 ===');
  
  const testStrings = [
    '下载.png',
    '微信图片.jpg',
    '公司文档.pdf'
  ];
  
  testStrings.forEach(str => {
    console.log(`\n原始字符串: ${str}`);
    
    // 转换为latin1（模拟乱码）
    const latin1Buffer = Buffer.from(str, 'utf8');
    const latin1String = latin1Buffer.toString('latin1');
    console.log(`转换为latin1: ${latin1String}`);
    
    // 从latin1转换回UTF-8
    const utf8Buffer = Buffer.from(latin1String, 'latin1');
    const utf8String = utf8Buffer.toString('utf8');
    console.log(`转换回UTF-8: ${utf8String} ${utf8String === str ? '✅' : '❌'}`);
  });
}

/**
 * 模拟Multer文件名处理逻辑
 */
function simulateMulterProcessing() {
  console.log('\n=== 模拟Multer处理逻辑 ===');
  
  const mockFiles = [
    { originalname: 'ä¸è½½.png', filename: 'file-123.png', mimetype: 'image/png' },
    { originalname: 'æµè½½.pdf', filename: 'file-456.pdf', mimetype: 'application/pdf' },
    { originalname: 'test.docx', filename: 'file-789.docx', mimetype: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }
  ];
  
  mockFiles.forEach((file, index) => {
    console.log(`\n文件 ${index + 1}:`);
    console.log(`  originalname: ${file.originalname}`);
    console.log(`  filename: ${file.filename}`);
    console.log(`  mimetype: ${file.mimetype}`);
    
    let decodedOriginalName = file.originalname;
    
    try {
      // 检查是否是URL编码
      if (file.originalname.includes('%')) {
        decodedOriginalName = decodeURIComponent(file.originalname);
        console.log(`  ✅ URL解码成功: ${file.originalname} -> ${decodedOriginalName}`);
      }
      // 检查是否是UTF-8乱码
      else if (/[äåçèéêëìíîïðñòóôõöøùúûüýþÿ]/.test(file.originalname)) {
        try {
          const buffer = Buffer.from(file.originalname, 'latin1');
          decodedOriginalName = buffer.toString('utf8');
          console.log(`  ✅ UTF-8解码成功: ${file.originalname} -> ${decodedOriginalName}`);
        } catch (bufferError) {
          console.log(`  ❌ UTF-8解码失败: ${bufferError.message}`);
        }
      }
      // 检查是否包含中文字符但显示正常
      else if (/[\u4e00-\u9fa5]/.test(file.originalname)) {
        console.log(`  ✅ 中文文件名正常: ${file.originalname}`);
      }
      else {
        console.log(`  ℹ️ 英文文件名: ${file.originalname}`);
      }
    } catch (error) {
      console.log(`  ❌ 文件名解码失败: ${error.message}`);
    }
    
    console.log(`  最终文件名: ${decodedOriginalName}`);
  });
}

// 运行测试
if (require.main === module) {
  testUtf8Decoding();
  testBufferConversion();
  simulateMulterProcessing();
}

module.exports = {
  testUtf8Decoding,
  testBufferConversion,
  simulateMulterProcessing
};
